package com.ciwong.epaper.modules.me.presenter;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.common.guidedialog.ChooseReadDialog;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.ui.SpeechPlayController;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.interactivetutorial.InteractiveTutorialCordovaActivity;
import com.ciwong.epaper.modules.me.bean.CheckValidBean;
import com.ciwong.epaper.modules.me.bean.MenuOptionBean;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.ui.interfaces.IHomeWorkFragment;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerCordovaActivity;
import com.ciwong.epaper.modules.scan.bean.EpaperQRInfo;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.widget.NewBottomMenuDialog;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class HomeWorkPresenter implements IHomeWorkPresenter {

    private final String TAG = "HomeWorkPresenter";

    public static final long DELAY_TIME_INTERACTIVE_TUTORIAL = 2000;
    private final IHomeWorkFragment homeWorkFragment;
    private final Activity mActivity;
    private NewBottomMenuDialog bottomMenuDialog;
    private MyWork mCurrentMyWork;
    private WorkContents mCurrentWorkContents;
    /**
     * 网络请求完成以后是否跳转到学习界面
     */
    private int mGroupPosition;
    private int mChildPosition;
    private DownLoadInfo mCurrentDownloadInfo;
    /**
     * 作业类型 0做作业，1订正错题
     */
    private int doWorkType = 0;

    /**
     * 是否是课堂作业
     */
    private boolean isClassWork;

    private Handler handler = new Handler();

    public HomeWorkPresenter(IHomeWorkFragment homeWorkFragment, Activity mActivity) {
        this.homeWorkFragment = homeWorkFragment;
        this.mActivity = mActivity;
    }

    @Override
    public boolean onChildClick(MyWork myWork, WorkContents workContent, int groupPosition, int childPosition, int doWorkType, boolean isClassWork) {
        this.mGroupPosition = groupPosition;
        this.mChildPosition = childPosition;
        this.mCurrentMyWork = myWork;
        this.doWorkType = doWorkType;
        this.isClassWork = isClassWork;
        this.mCurrentWorkContents = workContent;
        boolean isSubmit = false;
        if (doWorkType == 1) {
            if (workContent.getErrorWorkId() != null && workContent.getErrorWorkId().length() > 1) {
                isSubmit = true;
            }
        } else {
            if (workContent.getDoWorkId() != null && workContent.getDoWorkId().length() > 1) {
                isSubmit = true;
            }
        }
        if (null != workContent && workContent.feedback == 1 && workContent.getExamMode() == 0 && workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
//            setBottomMenuDialog(myWork, workContent, groupPosition, childPosition, doWorkType);
            initJumpToParam(myWork, workContent, groupPosition, childPosition, doWorkType);
//            CWLog.e(TAG, "jumpToWork: 听说模考");
        } else if (!(workContent.getSubmitCount() > 0 && isSubmit)) {
            //未提交过，未做过作业
            initJumpToParam(myWork, workContent, groupPosition, childPosition, doWorkType);
        } else {//做过作业，或者提交过作业
            if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) { //当是互动教程时
                //查看详情
                checkExamATime(groupPosition, childPosition, doWorkType);
                return true;
            }
            setBottomMenuDialog(myWork, workContent, groupPosition, childPosition, doWorkType);
        }
        return true;
    }

    @Override
    public void onDownloadProgressDismissListener(DialogInterface dialog) {
        try {
            if (mCurrentDownloadInfo != null) {
                int status = mCurrentDownloadInfo.getStatus();
                if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                    DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    /**
     * 添加本地数据
     *
     * @param key
     */
    public void loadLocalData(String key) {
        homeWorkFragment._showCricleProgress(null);

        SerializableManager.getInstance().deSerialize(key, new BaseCallBack() {
            @Override
            public void success(Object data) {
                homeWorkFragment.loadLocalDataSucess(data);
            }

            @Override
            public void failed(int errorCode, Object data) {
                homeWorkFragment.refreshNetData(true);
            }

            @Override
            public void failed(Object data) {
                homeWorkFragment.refreshNetData(true);
            }
        });

    }


    /**
     * 获取作业通知列表
     */
    public void getMyWorkList(int workMode, int curPage, int LOAD_PAGE_SIZE, boolean isErrorWork, boolean isClassWork) {
        homeWorkFragment.setEnablePullLoadMoreDataStatus(true);
        if (null == EApplication.getInstance().getUserInfoBase()) {
            return;
        }
        EpaperDao.getInstance().getMyWork(EApplication.BRAND_ID, workMode, curPage, LOAD_PAGE_SIZE, 0, isErrorWork, isClassWork, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                BasePaging<MyWork> workNotifyBasePaging = (BasePaging<MyWork>) data;
                CopyOnWriteArrayList<MyWork> list = new CopyOnWriteArrayList<MyWork>(workNotifyBasePaging.getPageList());
                homeWorkFragment.getMyWorkListSucess(workNotifyBasePaging, list);
                if (list != null) {
                    getDownloadingTaskAndRefresh(list);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                failed(data);
            }

            @Override
            public void failed(Object data) {
                homeWorkFragment.getMyWorkListFail(data, getUrl());
            }
        });

    }

    /**
     * 匹配刷新下载状态
     *
     * @param myWorksList
     */
    private void getDownloadingTaskAndRefresh(final List<MyWork> myWorksList) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                List<DownLoadInfo> downLoadInfoList = DownLoadDB.queryUnCompletedList();
                if (downLoadInfoList != null && !downLoadInfoList.isEmpty()) {
                    for (Iterator iterator = myWorksList.iterator(); iterator.hasNext(); ) {
                        MyWork myWork = (MyWork) iterator.next();

                        List<WorkContents> workContentsList = myWork.getWorkContents();

                        for (Iterator iterator1 = workContentsList.iterator(); iterator1.hasNext(); ) {
                            WorkContents tempWorkContent = (WorkContents) iterator1.next();

                            DownLoadInfo tempInfo = new DownLoadInfo();
                            tempInfo.setIsEqualsWork(true);
                            tempInfo.setBookId(tempWorkContent.getPackageId());
                            tempInfo.setChapterId(tempWorkContent.getcId());
                            int index = downLoadInfoList.indexOf(tempInfo);
                            if (index != -1) {
                                DownLoadInfo info = downLoadInfoList.get(index);
                                if (tempWorkContent.getcId().equals(info.getChapterId()) && tempWorkContent.getPackageId().equals(info.getBookId())) {
                                    tempWorkContent.setDownloadStatus(info.getStatus());
                                }
                            }
                        }
                    }
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            homeWorkFragment.notifyDataSetChanged();

                        }
                    });
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    public void setBottomMenuDialog(final MyWork myWork, final WorkContents workContents, final int groupPosition, final int childPosition, int doWorkType) {
        bottomMenuDialog = new NewBottomMenuDialog(mActivity);
        if (isClassWork) {
            //查看详情
            checkExamATime(mGroupPosition, mChildPosition, doWorkType);
            return;

        } else if (null != workContents && workContents.getExamMode() == 0 && workContents.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            SpannableString spannableString = new SpannableString(mActivity.getString(R.string.look_detail_correct));
            //设置字号
            AbsoluteSizeSpan span = new AbsoluteSizeSpan(DisplayUtils.sp2px(mActivity, 14));
            //设置颜色
            ForegroundColorSpan greenSpan = new ForegroundColorSpan(mActivity.getResources().getColor(R.color.look_detail_tips));
            spannableString.setSpan(greenSpan, 4, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(span, 4, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_dictation_again, "再做一次"));
            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_look_detail, spannableString));
        } else if (workContents != null && (workContents.getExamMode() == 0 || doWorkType == 1)) {
            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_dictation_again, "再做一次"));
            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_look_detail, "查看详情"));
//            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_ranking_chart, "排行榜"));
        } else {
            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_look_detail, "查看详情"));
//            bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_ranking_chart, "排行榜"));
        }
        bottomMenuDialog.setOtherStyle(true);
        bottomMenuDialog.setOnItemClickListener(bgOnItemClickListener);
        bottomMenuDialog.show();
    }


    private AdapterView.OnItemClickListener bgOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mCurrentWorkContents != null && (mCurrentWorkContents.getExamMode() == 0 || doWorkType == 1)) {
                switch (position) {
                    case 0:// 再次跟读
                        initJumpToParam(mCurrentMyWork, mCurrentWorkContents, mGroupPosition, mChildPosition, doWorkType);
                        break;
                    case 1://查看详情
                        checkExamATime(mGroupPosition, mChildPosition, doWorkType);
                        break;
                    case 2:// 排行榜
                        MeJumpManager.jumpToRankH5Activity(R.string.go_back, mActivity, mCurrentWorkContents.contentId + "", mCurrentWorkContents.getResourceName());
                        break;
                    default:
                        break;
                }
            } else {
                switch (position) {
                    case 0://查看详情
                        checkExamATime(mGroupPosition, mChildPosition, doWorkType);
                        break;
                    case 1:// 排行榜
                        MeJumpManager.jumpToRankH5Activity(R.string.go_back, mActivity, mCurrentWorkContents.contentId + "", mCurrentWorkContents.getResourceName());
                        break;
                    default:
                        break;
                }
            }

            if (null != bottomMenuDialog && bottomMenuDialog.isShowing()) {
                bottomMenuDialog.dismiss();
            }
        }
    };

    public void checkExamATime(int groupPosition, int childPosition, int doWorkType) {
        boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotSeeWorkAnswer((BaseActivity) mActivity, mCurrentMyWork, mCurrentWorkContents, doWorkType);
        if (!orNotWatchDetails) {
            return;
        }
//        if (mCurrentWorkContents.getIsValid() == 0) {
//            //服务不可用。不可查看
//            setBuyServiceDialog();
//            return;
//        }
        jumpToNewStudyRecordH5(mCurrentWorkContents);
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(mActivity);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    if (mCurrentMyWork.getServiceType() > 0) {
                        //购买服务包
                        MeJumpManager.jumpBuyService(mActivity, R.string.go_back, mCurrentMyWork.getServiceType(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    } else {
                        //拓展服务
                        MeJumpManager.jumpToResourseCenterH5Activity(mActivity, R.string.go_back, mActivity.getString(R.string.resource_center));
                    }
                    buyServiceDialog.dismiss();

                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    private void jumpToNewStudyRecordH5(WorkContents workContent) {
        String url = "";
        String pageType = "0";
        if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            url = EpaperConstant.URL_LSW_DETAILS;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {
            if (workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_WORD)/*||workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT*/) {
                pageType = "1";
            } else if (workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_SENTENCES)
                    || workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_LESSON)
                    || workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_TEXT)) {
                pageType = "3";
            }
            url = EpaperConstant.URL_READING_REPEAD + "pageType=" + pageType + "&parentVersionId=" + workContent.parentVersionId;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) {
            pageType = "1";
            url = EpaperConstant.URL_H5_DICATION + "pageType=" + pageType;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {//在线作答
            pageType = "1";
            url = EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5 + "pageType=" + pageType;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) {//互动教程
            pageType = "1";
            url = EpaperConstant.URL_INTERACTIVE_TUTORIAL_DETAIL_H5 + "pageType=" + pageType;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DUBBING) {//趣味配音
            //点击更多配音记录详情
            MeJumpManager.jumpToDubVideoRecordDetailH5Activity(mActivity, R.string.go_back, "", workContent.getDoWorkId());
            return;
        }
        StringBuffer sb = new StringBuffer(url);
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long userId = EApplication.getInstance().getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(userId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append(workContent.getVersionId());
        sb.append("&doWorkId=");
        if (doWorkType == 1) {
            sb.append(workContent.getErrorWorkId());
        } else if (null != workContent && workContent.feedback == 1 && workContent.getExamMode() == 0 && workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            sb.append(workContent.getFeedbackDoWorkId());
        } else {
            sb.append(workContent.getDoWorkId());
        }
        if (url.equals(EpaperConstant.URL_LSW_DETAILS) && !isClassWork) {
            sb.append("&revisedMode=1");
        }
        sb.append("&doWorkType=");
        sb.append(doWorkType);
        sb.append("&disableChoiceAndFillRevised=1");
        if (isClassWork) {
            sb.append("&doClassWorkType=");
            sb.append(1);
        }

        String title;
        try {
            title = java.net.URLEncoder.encode(workContent.getResourceName(), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            title = "";
        }
        title = title.replace("+", "%20");
        sb.append("&title=");
        sb.append(title);
        MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, mActivity, R.string.go_back, -1, sb.toString(), workContent.getResourceName(), 0);
    }


    /**
     * @param myWork
     * @param workContent
     * @param groupPosition
     * @param childPosition
     */
    public void initJumpToParam(final MyWork myWork, final WorkContents workContent, final int groupPosition, final int childPosition, final int doWorkType) {
        homeWorkFragment._showDownloadProgress("玩命加载中,请耐心等待......");
        try {
            if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                //视频讲解点播视频再判断
                validSuccess(workContent, groupPosition, childPosition, myWork);
            } else if (workContent.workTag == ModuleInfo.ModuleInfoId.WORK_TAG_EXAM) {//试卷
                MeJumpManager.jumpToExamCordovaActivity(mActivity, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getServiceType(), workContent, 1, mCurrentMyWork.getEffectiveDate());
                homeWorkFragment._hideCricleProgress();
            } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_DUBBING) {//趣味配音
                WorkContent workCont = new WorkContent();
                workCont.setVersionId(workContent.getVersionId());
                workCont.setResourceName(workContent.getResourceName());
                workCont.setWorkType(myWork.getServiceType());
                workCont.setParentVersionId(workContent.getParentVersionId());
                workCont.setPackageId(workContent.getPackageId());
                workCont.setcId(workContent.getcId());
                workCont.setModuleId(workContent.getModuleId());
                workCont.setStartTime(workContent.getNowDate() * 1000);
                workCont.setIsFree(workContent.getIsFree());
                MeJumpManager.jumpToDubVideoDetailActivity(EpaperConstant.REQUEST_CODE_GET_VIDEO_MASTER_STATE, R.string.go_back,
                        mActivity, myWork.getWorkId(), workCont, myWork.getClassId(), workContent.getContentId(), true);
                homeWorkFragment._hideCricleProgress();
            } else {
                EpaperRequest.checkValid(EApplication.BRAND_ID + "", myWork.getServiceType() + "", workContent.getPackageId(), workContent.getcId(), null, workContent.getExamMode(), new BaseExtCallBack(mActivity) {
                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        homeWorkFragment._hideDownloadProgress();
                        if (errorCode == 5201) {
                            ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(data.toString(), errorCode);
                        } else {
                            if (null != data && errorCode != 17 && errorCode != 27) {
                                ToastUtil.INSTANCE.toastCenterNoNetErrorOrServerError();
                            }
                        }
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查权限失败" + getUrl(), true);

                    }

                    @Override
                    public void failed(Object data) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.server_error);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查权限失败" + getUrl(), true);
                        homeWorkFragment._hideDownloadProgress();
                    }

                    @Override
                    public void success(Object data) {
                        if (data == null) {
                            ToastUtil.INSTANCE.toastCenterError("检查权限失败!");
                            homeWorkFragment._hideDownloadProgress();
                        } else {
                            CheckValidBean checkValidBean = (CheckValidBean) data;
                            long nowData = checkValidBean.getNowData();
                            if (null != workContent) {
                                workContent.setStartTime(nowData);
                            }
                            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotDowork((BaseActivity) mActivity, myWork, workContent, doWorkType, nowData / 1000);
                            if (orNotWatchDetails) {
                                if (checkValidBean != null && checkValidBean.isValid == 1) { //有权限
                                    validSuccess(workContent, groupPosition, childPosition, myWork);
                                } else {//没有权限
                                    int serviceType = myWork.getServiceType();
                                    if (serviceType == 0 && checkValidBean.services != null && !checkValidBean.services.isEmpty()) {
                                        serviceType = checkValidBean.services.get(0).id;
                                    }
                                    MeJumpManager.jumpBuyService(mActivity, R.string.go_back, serviceType, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                                    homeWorkFragment._hideDownloadProgress();
                                }
                            } else {
                                homeWorkFragment._hideDownloadProgress();
                            }
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideCricleProgress();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    /**
     * 判断权限成功
     *
     * @param workContent
     * @param groupPosition
     * @param childPosition
     * @param myWork
     */
    private void validSuccess(WorkContents workContent, int groupPosition, int childPosition, MyWork myWork) {
        try {
            DownLoadInfo downLoadInfoNew = DownLoad.getInstance().isPackageExist_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());
            DownLoadInfo downLoadInfo = DownLoad.getInstance().isPackageExist(workContent.getPackageId(), workContent.getcId());
            String mainJsonPath = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(workContent.getPackageId(), workContent.getcId());
            String resourcePath = ESystem.getPackagesResourcePath(workContent.getPackageId(), workContent.getcId());
            //资源不存在,而且本地也没有，就去下载了
            if (downLoadInfoNew == null && downLoadInfo == null) {
                downLoadWork(workContent, groupPosition, childPosition);
            } else {
                if (downLoadInfoNew != null) {
                    //新资源
                    File packagesCatalogueFile_New = new File(ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    File packagesCatalogueMediaFile_New = new File(ESystem.getPackagesMediaPath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));

                    File packagesCatalogueResourceFile_New = new File(ESystem.getPackagesResourcePath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER || workContent.workTag == 2) {//线上作答和试卷不验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueResourceFile_New.exists()
                                && packagesCatalogueResourceFile_New.list().length > 0) {//lzh添加此处判断，解决资源文件内容被删除后打不开
                            //是线上作答先不隐藏，防止下载离线html包引起的无进度圈，用户再次点击会打开多个线上作答
                            if (!ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId())) {
                                homeWorkFragment._hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {//没有下载过，或者有部分文件被勿删过。
                            downLoadWork(workContent, groupPosition, childPosition);
                        }
                    } else {//其他作业需要验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueMediaFile_New.exists() && packagesCatalogueResourceFile_New.exists()
                                && packagesCatalogueResourceFile_New.list().length > 0) {//lzh添加此处判断，解决资源文件内容被删除后打不开
                            if (!ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId())) {
                                homeWorkFragment._hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {//没有下载过，或者有部分文件被勿删过。
                            downLoadWork(workContent, groupPosition, childPosition);
                        }
                    }
                } else if (downLoadInfo != null) { //旧资源
                    if (!new File(mainJsonPath).exists() || !new File(catalogueJsonPath).exists() || !new File(resourcePath).exists() //作业的那几个文件和文件夹都必须存在，不然就得重新下载，防止人为删除文件夹后点击无反映的问题。
                            || !(new File(resourcePath).list().length > 0)) {//lzh添加判断文件是否存在
                        downLoadWork(workContent, groupPosition, childPosition);
                    } else if (new File(mainJsonPath).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists()) { //下载的所有文件都必须没有丢失，否则就去下载
                        checkUpdate(myWork, workContent, downLoadInfo, groupPosition, childPosition);//检查资源有没有更新
                    } else {
                        downLoadWork(workContent, groupPosition, childPosition);
                    }
                }
            }

        } catch (Exception e) {
            homeWorkFragment._hideDownloadProgress();
            e.getStackTrace();
        }
    }


    /**
     * 下载作业
     */
    private void downLoadWork(WorkContents workContents, int groupPosition, int childPosition) {
        try {
            homeWorkFragment._showCancelButtonOfDownloadProgress();
            if (!NetworkUtils.isOnline()) {
//                toastInCenter("网络不可用，请连接网络后重试");
//                homeWorkRelatPresenter.getHandler().sendEmptyMessage(NET_ERROR_TIP);//子线程，无法直接吐司.
            }
            DownLoadInfo tempInfo = new DownLoadInfo();
            tempInfo.setSavePath(DownLoad.getInstance().getDownloadPathById(workContents.getPackageId(), workContents.getcId()));
            DownLoadInfo info = DownLoad.getInstance().getCurrentBean(tempInfo);

            // 不存在下载队列中添加到下载队列, 失败了重新请求地址重下
            if (info == null || info.getStatus() == DownloadStatus.STATUS_FAILED
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_SDISFULL
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                //if (TextUtils.isEmpty(workContents.resourceUrl)) {//旧资源需要重新请求下载地址。
                getCatalogueInfoAction(workContents, workContents.getcId(), groupPosition, childPosition);
            } else {
                //解决 弱网情况下 下载没有回调问题，把任务挂起 后继续下载
                DownLoad.getInstance().pauseTask(info);
                DownLoad.getInstance().resumeTask(info);
                // 下载状态
                switch (info.getStatus()) {
                    case DownloadStatus.STATUS_PAUSE:
                        DownLoad.getInstance().resumeTask(info);
                        break;
                    case DownloadStatus.STATUS_FAILED:
                    case DownloadStatus.STATUS_FAILED_SDISFULL:
                    case DownloadStatus.STATUS_FAILED_UNZIP:
                        DownLoad.getInstance().addTask(info);
                        break;
                    case DownloadStatus.STATUS_LOADING:
                    case DownloadStatus.STATUS_DOWNLOADING:
                        break;
                    case DownloadStatus.STATUS_UPZIPING:
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    public static String getSavePathByUrl(Activity activity, String url) {
//        FileUtil.getSavePathByUrl(url);
        String cacheDir = activity.getApplicationContext().getExternalCacheDir().getAbsolutePath();
        final String path = cacheDir + File.separator
                + "base";
        File f = new File(path);
        if (!f.exists()) {
            new File(f, ".nomedia").mkdirs();
        }

        try {
            //因为服务器缓存问题,如果资源重新发布,需要在下载地址文件名后面加上时间戳
            //客户端在下载保存的时候要去掉时间戳
            String workName = url.substring(url.lastIndexOf("/"));
            String pathDownload = path + File.separator + "download";
            File fDownload = new File(pathDownload);
            if (!fDownload.exists()) {
                fDownload.mkdirs();
            }
            if (workName.contains("v")) {
                return fDownload + workName.substring(0, workName.indexOf("v") - 1) + ".res";
            } else {//原有的逻辑  没有改过资源的
                return fDownload + url.substring(url.lastIndexOf("/"));
            }


        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取章节目录信息以及下载地址
     *
     * @param cId
     */
    private void getCatalogueInfoAction(final WorkContents workContents, final String cId, final int groupPosition, final int childPosition) {
        try {
            EpaperDao.getInstance().getCatalogueInfoNew(workContents.getPackageId(), cId, workContents.getModuleId() + "", workContents.getVersionId() + "", new BaseExtCallBack(mActivity) {

                @Override
                public void success(Object data) {
                    try {
                        EpaperQRInfo epaperQRInfo = (EpaperQRInfo) data;
                        String url = epaperQRInfo.getDownLoadUrl();

                        //测试地址  url="https://file.dzb.ciwong.com/epaper/20170912145905/catalogue_5238_6141001_v1505199545.res";
                        final DownLoadInfo downLoadInfo = new DownLoadInfo();
                        if (groupPosition != -1) {
                            downLoadInfo.setSubjectId(mCurrentMyWork.subjectId);
                        }
                        downLoadInfo.setType(epaperQRInfo.getcType());
                        downLoadInfo.setResourceName(workContents.getResourceName());
                        downLoadInfo.setResourceType(workContents.getResourceType());
                        downLoadInfo.setBookId(epaperQRInfo.getPackageId());
                        downLoadInfo.setBookName(epaperQRInfo.getPackageName());
                        downLoadInfo.setIconUrl(epaperQRInfo.getPackageCover());
                        downLoadInfo.setChapterId(epaperQRInfo.getcId());
                        downLoadInfo.setChapterName(epaperQRInfo.getcName());
                        downLoadInfo.setResourceName(workContents.getResourceName());
                        downLoadInfo.setResourceType(workContents.getResourceType());
                        //旧资源不用存moduleId 和versionId
                        downLoadInfo.setModuleId(workContents.getModuleId() + "");
                        downLoadInfo.setVersionId(workContents.getVersionId());
                        downLoadInfo.setUrl(url);

                        downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(mActivity, url));
                        downLoadInfo.setStatus(DownloadStatus.STATUS_LOADING);
                        downLoadInfo.setHash(epaperQRInfo.getHash());
                        String fileSize = epaperQRInfo.getFileSize();
                        downLoadInfo.groupPosition = groupPosition;
                        downLoadInfo.childPosition = childPosition;
                        if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                            downLoadInfo.setSize(fileSize.split(" ")[0]);
                        }

                        if (DialogUtil.sdIsFullForDownload(mActivity, downLoadInfo)) {
                            DialogUtil.showSdFullDialog(mActivity, downLoadInfo.getSize());
                            return;
                        }
                        if (NetworkUtils.isWifiOnline()) {
                            DownLoad.getInstance().addTask(downLoadInfo);

                        } else {
                            homeWorkFragment._hideDownloadProgress();
                            homeWorkFragment._showWIFIDialog(downLoadInfo);

                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                        homeWorkFragment._hideDownloadProgress();
                    }
                }

                @Override
                public void failed(int errorCode, Object data) {
                    homeWorkFragment._hideDownloadProgress();
                    String errorMsg = data == null ? "" : data.toString();
                    String logDec = "packageId:" + workContents.getPackageId() + ",cId:" + cId + errorCode + ",errorMsg:" + errorMsg;
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                    ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");
                }

                @Override
                public void failed(Object data) {
                    homeWorkFragment._hideDownloadProgress();
                    String errorMsg = data == null ? "" : data.toString();
                    String logDec = "packageId:" + workContents.getPackageId() + "mcId:" + cId + ",errorMsg:" + errorMsg;
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                    ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");
                }
            });
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    private void jumpToWork(final WorkContents workContent, final DownLoadInfo downLoadInfo, final MyWork myWork) {
        CheckIsExamForDetail.INSTANCE.checkExamATime(myWork.getEffectiveDate(), workContent.getContentId() + "", workContent.getNowDate(), workContent.getExamMode(), workContent.getSeeWorkMode(), workContent.getSubmitMode());
        try {
            setWorkNotifyReadAction(myWork.workId);
            if (null != downLoadInfo) {
                if (workContent.getStartTime() > 0) {
                    downLoadInfo.setStartTime(workContent.getStartTime());
                } else {
                    downLoadInfo.setStartTime(workContent.getNowDate() * 1000);
                }
            }
            int moduleId = workContent.getModuleId();
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY) {//时文
                if (homeWorkFragment._isProgressBarShowing()) {
                    downLoadInfo.setVersionId(workContent.getVersionId());
                    MeJumpManager.jumpToTimeNewsH5Activity(R.string.go_back, mActivity, downLoadInfo, null, 0);
                }
            }  // 同步测试
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                String packagesJsonPath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), downLoadInfo.getVersionId());

                if (new File(packagesJsonPath).exists()) {
                    if (homeWorkFragment._isProgressBarShowing()) {
                        EpaperJumpManager.jumpToDictaion(R.string.go_back, mActivity, downLoadInfo, null, 0);
                    }
                    return;
                }
                homeWorkFragment._showToastSuccess(R.string.offline_answer);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {

                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(mActivity);
                    return;
                }
                String resourceModuleId = downLoadInfo.getResourceType();

                String requirementContent = workContent.getRequirementContent();
                RequirementContent rc = null;
                if (!TextUtils.isEmpty(requirementContent)) {
                    rc = new Gson().fromJson(requirementContent, RequirementContent.class);
                }
                if (rc == null) {
                    ChooseReadDialog dialog = new ChooseReadDialog(mActivity, myWork.workId, downLoadInfo, null, 0, resourceModuleId, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, myWork.getEffectiveDate());
                    dialog.show();
                } else {
                    int speakType;
                    if (resourceModuleId.equals(ModuleContent.ResourceType.RESOURCE_TYPE_LESSON)) {
                        // 句子
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_REPEAT:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechPlayController.LISTENER_MODE_DULI;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_RECITE:
                                speakType = SpeechPlayController.LISTENER_MODE_XUANDUAN;
                                break;
                            default:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;
                        }
                        CWLog.e(TAG, "jumpToWork: 句子");
                        EpaperJumpManager.jumpToSentenceRead(R.string.go_back, mActivity, myWork.workId, downLoadInfo, null, rc, 0, speakType, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, workContent.contentId, workContent, myWork.getEffectiveDate());
                    } else { // 单词
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechUtils.WordReadMode.READ_THROUGH;
                                break;
                            default:
                                speakType = SpeechUtils.WordReadMode.READ_REPEAT;
                                break;
                        }
                        CWLog.e(TAG, "jumpToWork: 单词");
                        EpaperJumpManager.jumpToWordRead(R.string.go_back, mActivity, myWork.workId, downLoadInfo, null, rc, 0, speakType, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());
                    }
                }


            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(mActivity);
                    return;
                }
                CWLog.e(TAG, "jumpToWork: 听说模考");
                EpaperJumpManager.jumpToListenSpeakWorkNew(R.string.go_back, (BaseActivity) mActivity, false, myWork.getWorkId(), myWork.getEffectiveDate(), downLoadInfo, myWork.classId, workContent.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE, myWork.getServiceType(), workContent, 0, doWorkType);

            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) {
                //报听写
                EpaperJumpManager.jumpToDictaionNew(R.string.go_back, mActivity, myWork.workId, downLoadInfo, null, 0, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());

            } // 视频讲解，h5 页面  123 or 126
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                CWLog.e(TAG, "jumpToWork: 视频讲解");
                ViedoJumpManager.jumpToNewVideoExplationActivity(R.string.go_back, mActivity, downLoadInfo, null, 0, workContent.getCommentContent(), workContent.getResourceName(), myWork.getServiceType(), null, null, myWork.classId);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                CWLog.e(TAG, "jumpToWork: 在线作答");
                MeJumpManager.jumpToNewOnlineAnswerCordovaActivity(mActivity, null, null, downLoadInfo, 0, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getEffectiveDate(), workContent.contentId, 1, myWork.getServiceType(), workContent, doWorkType);

            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) {//互动教程
                CWLog.e(TAG, "jumpToWork: 互动教程");
                MeJumpManager.jumpToNewBookDetailH5Activity((BaseActivity) mActivity, null, null, downLoadInfo, 0, myWork.getServiceType(), InteractiveTutorialCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), workContent.contentId, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK);
            }
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }


    //检查资源包是否有更新
    public void checkUpdate(final MyWork myWork, final WorkContents workContent, final DownLoadInfo oldloadInfo, final int groupPosition, final int childPosition) {//检查离线包是否更新
        EpaperDao.getInstance().getCatalogueInfoNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId(), new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                try {
                    EpaperQRInfo info = (EpaperQRInfo) data;
                    if (oldloadInfo != null && info != null) {
                        if (!info.getHash().equals(oldloadInfo.getHash())) { //资源包有更新 删除本地文件  并且重新下载
                            String path = "";
                            if (oldloadInfo.getType() == 1) {//新资源
                                path = ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());//资源包地址
                            } else {//旧资源
                                path = ESystem.getPackagesCatalogue(workContent.getPackageId(), workContent.getcId());//资源包地址
                            }
                            FileUtils.delete(path);
                            downLoadWork(workContent, groupPosition, childPosition);//重新下载

                        } else {//没有更新   则走原来逻辑
                            failed("没有更新");
                        }
                    } else {
                        failed(data);//没有更新   则走原来逻辑
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                    homeWorkFragment._hideDownloadProgress();
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查更新失败"+getUrl());
                failed("检查更新失败");
            }

            @Override
            public void failed(Object data) {
                try {
                    //                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查更新失败" + getUrl());
                    if (!ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId())) {
                        homeWorkFragment._hideDownloadProgress();
                    }

                    DownLoadInfo downLoadInfo = new DownLoadInfo();
                    if (oldloadInfo == null) {
                        downLoadInfo.setBookId(workContent.getPackageId());
                        downLoadInfo.setChapterId(workContent.getcId());
                        if (!TextUtils.isEmpty(workContent.resourceUrl)) {//新资源
                            downLoadInfo.setType(1);
                            downLoadInfo.setModuleId(workContent.getModuleId() + "");
                            downLoadInfo.setVersionId(workContent.getVersionId());
                        }
                    } else {
                        downLoadInfo = oldloadInfo;
                    }
                    if (data instanceof String && data.toString().equals("检查更新失败")) {
                        localJumpAction(myWork, workContent, downLoadInfo, true);
                    } else {
                        localJumpAction(myWork, workContent, downLoadInfo, false);
                    }

                } catch (Exception e) {
                    e.getStackTrace();
                    homeWorkFragment._hideDownloadProgress();
                }

            }
        });
    }

    /**
     * 获取Module信息后跳转至做作业
     *
     * @param workContent
     * @param downLoadInfo
     */
    private void localJumpAction(final MyWork myWork, final WorkContents workContent, final DownLoadInfo downLoadInfo, final boolean isCheckUpdateFail) {
        try {
            String path = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            EpaperDao.getInstance().getSerializableObjects(path, Main.class,

                    new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            homeWorkFragment._hideDownloadProgress();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            homeWorkFragment._hideDownloadProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Main数据失败");
                            if (downLoadInfo.getStatus() != DownloadStatus.STATUS_UPZIPING) {
                                super.failed(errorCode, data);
                            }
                        }

                        @Override
                        public void success(Object data) {
                            Main main = (Main) data;
                            getCatalogueFile(myWork, workContent, downLoadInfo, main.getCatalogueFile(), main.getJsonVersion(), isCheckUpdateFail);
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    /**
     * 获取目录内容信息
     *
     * @param workContent  目录内容信息地
     * @param downLoadInfo
     * @param path
     * @param jsonVersion
     */
    private void getCatalogueFile(final MyWork myWork, final WorkContents workContent, final DownLoadInfo downLoadInfo, String path, final String jsonVersion, final boolean isCheckUpdateFail) {
        try {
            path = ESystem.getPackagesPath(mActivity) + File.separator + path;
            Type responseType = new TypeToken<List<Module>>() {
            }.getType();
            EpaperDao.getInstance().getSerializableObjects(path, responseType,
                    new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            homeWorkFragment._hideDownloadProgress();
                            CWLog.e(TAG, data.toString());
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            homeWorkFragment._hideDownloadProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源", true);
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void success(Object data) {
                            try {
                                List<Module> modules = (List<Module>) data;
                                Module module = HomeWorkUtil.getModule(modules, workContent);
                                if (module == null) {
                                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST, "解压后没有找到指定module", getRemarkNoFoundModule(workContent), true);
                                }
                                int index = HomeWorkUtil.getModuleContentIndex(module, workContent);
                                jumpToAction(myWork, workContent, downLoadInfo, module, index, jsonVersion, isCheckUpdateFail, doWorkType);
                            } catch (Exception e) {
                                e.getStackTrace();
                                homeWorkFragment._hideDownloadProgress();
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    private String getRemarkNoFoundModule(WorkContents workContent) {
        return workContent.getcId() + "_" + workContent.getPackageId() + "  " + workContent.getResourceName();
    }

    /**
     * 跳转动作
     *
     * @param workContent
     * @param downLoadInfo
     * @param module
     * @param index
     * @param jsonVersion
     */
    private void jumpToAction(final MyWork myWork, final WorkContents workContent, final DownLoadInfo downLoadInfo, final Module module, final int index, final String jsonVersion, boolean isCheckUpdateFail, final int doWorkType) {
        CheckIsExamForDetail.INSTANCE.checkExamATime(myWork.getEffectiveDate(), workContent.getContentId() + "", workContent.getNowDate(), workContent.getExamMode(), workContent.getSeeWorkMode(), workContent.getSubmitMode());
        try {
            final int moduleId = workContent.getModuleId();
            ModuleContent moduleContent = module.getResourceList().get(index);
            if (null != downLoadInfo) {
                if (workContent.getStartTime() > 0) {
                    downLoadInfo.setStartTime(workContent.getStartTime());
                } else {
                    downLoadInfo.setStartTime(workContent.getNowDate() * 1000);
                }
            }
            downLoadInfo.mJsonResPath = ESystem.getPackagesJsonPath(moduleContent.getResourceFile());
            if (index <= -1 && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_TRAIN && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                downLoadWork(workContent, -1, -1);
                if (isCheckUpdateFail) {
                    ToastUtil.INSTANCE.toastCenterError("检查更新失败，正在重新下载！");
                } else {
                    ToastUtil.INSTANCE.toastCenterError("获取资源失败，正在重新下载！");
                }
                homeWorkFragment._hideCricleProgress();
                return;
            }

            setWorkNotifyReadAction(myWork.workId);

            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY) {            // 作业类型时文
                MeJumpManager.jumpToTimeNewsH5Activity(R.string.go_back, mActivity, downLoadInfo, module, index);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {// 同步测试
                if (index > -1) {
                    String packagesJsonPath = ESystem.getPackagesJsonPath(module.getResourceList().get(index).getResourceFile());
                    if (new File(packagesJsonPath).exists()) {
                        EpaperJumpManager.jumpToDictaion(R.string.go_back, mActivity, downLoadInfo, module, index);
                        return;
                    }
                }
                homeWorkFragment._showToastSuccess(R.string.offline_answer);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {// 同步跟读
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(mActivity);
                    return;
                }
                String resourceModuleId = module.getResourceList().get(index).getResourceType();
                String requirementContent = workContent.getRequirementContent();
                RequirementContent rc = null;
                if (!TextUtils.isEmpty(requirementContent)) {
                    rc = new Gson().fromJson(requirementContent, RequirementContent.class);
                }
                if (rc == null) {
                    ChooseReadDialog dialog = new ChooseReadDialog(mActivity, myWork.workId, downLoadInfo, module, index, resourceModuleId, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, myWork.getEffectiveDate());
                    dialog.show();
                } else {
                    int speakType;
                    if (resourceModuleId.equals(ModuleContent.ResourceType.RESOURCE_TYPE_LESSON)) {
                        // 句子
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_REPEAT:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechPlayController.LISTENER_MODE_DULI;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_RECITE:
                                speakType = SpeechPlayController.LISTENER_MODE_XUANDUAN;
                                break;
                            default:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;
                        }
                        CWLog.e(TAG, "jumpToAction: 同步句子");
                        EpaperJumpManager.jumpToSentenceRead(R.string.go_back, mActivity, myWork.workId, downLoadInfo, module, rc, index, speakType, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, workContent.contentId, workContent, myWork.getEffectiveDate());
                    } else { // 单词
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechUtils.WordReadMode.READ_THROUGH;
                                break;
                            default:
                                speakType = SpeechUtils.WordReadMode.READ_REPEAT;
                                break;
                        }
                        CWLog.e(TAG, "jumpToAction: 同步单词");
                        EpaperJumpManager.jumpToWordRead(R.string.go_back, mActivity, myWork.workId, downLoadInfo, module, rc, index, speakType, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());
                    }
                }
            }
            // 听说模考
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(mActivity);
                    return;
                }
                ThreadTask.getInstance().executorDBThread(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CWLog.e(TAG, "jumpToAction: 听说模考");
                                EpaperJumpManager.jumpToListenSpeakWork(R.string.go_back, (BaseActivity) mActivity, myWork.workId, downLoadInfo, module, index, myWork.classId, jsonVersion, workContent.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE, myWork.getServiceType(), workContent, 0, doWorkType, false);

                            }
                        });
                    }
                }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
            }
            // 同步训练
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TRAIN) {
                homeWorkFragment._showToastSuccess(R.string.offline_answer);

            }
            // 报听写
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) {
                CWLog.e(TAG, "jumpToAction: 报听写");
                EpaperJumpManager.jumpToDictaionNew(R.string.go_back, mActivity, myWork.workId, downLoadInfo, module, index, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());

            }
            // 视频讲解，h5 页面  123 or 126
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                CWLog.e(TAG, "jumpToAction: 视频讲解");
                ViedoJumpManager.jumpToNewVideoExplationActivity(R.string.go_back, mActivity, downLoadInfo, module, index, workContent.getCommentContent(), workContent.getResourceName(), myWork.getServiceType(), null, null, myWork.classId);
            }
            // 在线作答
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                CWLog.e(TAG, "jumpToAction: 在线作答");
                MeJumpManager.jumpToNewOnlineAnswerCordovaActivity(mActivity, moduleContent, module, downLoadInfo, index, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getEffectiveDate(), workContent.contentId, 1, myWork.getServiceType(), workContent, doWorkType);
            }
            // 互动教程
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) {
                CWLog.e(TAG, "jumpToAction: 互动教程");
                MeJumpManager.jumpToInteractiveTutorialCordovaActivity((BaseActivity) mActivity, moduleContent, module, downLoadInfo, index, myWork.getServiceType(), InteractiveTutorialCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), workContent.contentId, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK);
            }
            //试卷
            else {// 其它类型
                homeWorkFragment._showToastError(R.string.no_support_work_type);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 作业通知回执
     *
     * @param workIds
     */
    private void setWorkNotifyReadAction(String workIds) {
        EpaperDao.getInstance().setWorkNotifyRead(workIds, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(Object data) {
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    @Override
    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        try {
            final DownLoadInfo downLoadInfo = item.getInfo();
            mCurrentDownloadInfo = downLoadInfo;
            if (downLoadInfo != null) {
                if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FILE_DOWNLOAD) {
                    homeWorkFragment._hideDownloadHorizontalProgressBar();
                    homeWorkFragment._hideCancelButtonOfDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_COMPLETED) {
                    //线上作答要去检查html离线包，所以下载完成先不隐藏下载框
                    if (mActivity != null && mActivity instanceof BaseActivity) {
                        if (((BaseActivity) mActivity).isTopActivity()) {
                            judgeDownloadInfoAndWorkContents(downLoadInfo, mCurrentWorkContents, mCurrentMyWork);
                        } else {
                            homeWorkFragment._hideDownloadProgress();
                        }
                    } else {
                        homeWorkFragment._hideDownloadProgress();
                    }

                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED
                        || downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP
                        || downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                    ToastUtil.INSTANCE.toastCenterError(R.string.download_fail);
                    homeWorkFragment._hideDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_DOWNLOADING) {
                    HomeWorkUtil.matchCurrentDownloadingHomework(downLoadInfo, mCurrentWorkContents, new HomeWorkUtil.ResoureTypeMatchListener() {
                        @Override
                        public void homeworkMatchSuccess(DownLoadInfo downLoadInfo) {
                            Log.e(TAG, "onEventMainThread STATUS_DOWNLOADING: " + downLoadInfo.getChapterName() + "  " + downLoadInfo.getResourceName() + "  progress" + downLoadInfo.getProgress());
                            homeWorkFragment._updateDownloadProgress(downLoadInfo.getProgress());
                        }

                        @Override
                        public void homeworkMatchFailed() {

                        }
                    });
                }
            } else {
                CWLog.e(TAG, "downLoadInfo == null:");
            }
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }
    }

    @Override
    public BroadcastReceiver getBroadcastReceiver() {
        return mBroadcastReceiver;
    }

    private void judgeDownloadInfoAndWorkContents(DownLoadInfo downLoadInfo, final WorkContents currentWorkContents, final MyWork currentMyWork) {
        //防止取消了仍会打开
        if (homeWorkFragment._isDownloadProgressBarShowing()) {
            if (ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(currentWorkContents.getModuleId())) {

            } else {
                homeWorkFragment._hideDownloadProgress();
            }
        }
        HomeWorkUtil.matchCurrentDownloadingHomework(downLoadInfo, currentWorkContents, new HomeWorkUtil.ResoureTypeMatchListener() {
            @Override
            public void homeworkMatchSuccess(DownLoadInfo downLoadInfo) {
                jumpToDoWorkAfterDownload(currentWorkContents, currentMyWork);
            }

            @Override
            public void homeworkMatchFailed() {
                homeWorkFragment._hideDownloadProgress();
            }
        });
    }

    /**
     * 下载完之后跳转作业方法
     */

    private void jumpToDoWorkAfterDownload(WorkContents workContent, MyWork myWork) {
        try {
            DownLoadInfo downLoadInfoNew = DownLoad.getInstance().isPackageExist_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());
            DownLoadInfo downLoadInfo = DownLoad.getInstance().isPackageExist(workContent.getPackageId(), workContent.getcId());
            String mainJsonPath = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(workContent.getPackageId(), workContent.getcId());
            String resourcePath = ESystem.getPackagesResourcePath(workContent.getPackageId(), workContent.getcId());

            //资源不存在,而且本地也没有，就去下载了
            if (downLoadInfoNew == null && downLoadInfo == null) {
                downLoadWork(workContent, -1, -1);
            } else {
                if (downLoadInfoNew != null) {
                    //新资源
                    File packagesCatalogueFile_New = new File(ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    File packagesCatalogueMediaFile_New = new File(ESystem.getPackagesMediaPath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));

                    File packagesCatalogueResourceFile_New = new File(ESystem.getPackagesResourcePath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    if (ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId()) || workContent.workTag == 2) {//线上作答和试卷不验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueResourceFile_New.exists()) {
                            if (workContent.workTag == 2) {
                                homeWorkFragment._hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {
                            //防止下载的包结构有问题，这时应该取消弹框
                            homeWorkFragment._hideDownloadProgress();
                        }
                    } else {//其他作业需要验证media文件夹

                        if (packagesCatalogueFile_New.exists() && packagesCatalogueMediaFile_New.exists() && packagesCatalogueResourceFile_New.exists()) {
                            homeWorkFragment._hideDownloadProgress();
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {
                            //防止下载的包结构有问题，这时应该取消弹框
                            homeWorkFragment._hideDownloadProgress();
                        }
                    }

                } else if (downLoadInfo != null) {
                    //旧资源
                    if (new File(mainJsonPath).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists()) { //下载的所有文件都必须没有丢失，否则就去下载
                        localJumpAction(myWork, workContent, downLoadInfo, false);//
                    } else {
                        //防止下载的包结构有问题，这时应该取消弹框
                        homeWorkFragment._hideDownloadProgress();
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            homeWorkFragment._hideDownloadProgress();
        }

    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (null != intent && EpaperConstant.ACTION_PACKAGE_DELETE.equals(intent.getAction())) {
                //删除了本地package ，刷新状态
                homeWorkFragment.notifyDataSetChanged();
            } else if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG.equals(intent.getAction())) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        homeWorkFragment.refreshNetData(true);
                    }
                }, DELAY_TIME_INTERACTIVE_TUTORIAL);

            } else if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH.equals(intent.getAction())) {
                //专门为互动教程 延时请求处理

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        homeWorkFragment.refreshNetData(true);
                    }
                }, DELAY_TIME_INTERACTIVE_TUTORIAL);
            } else if (EpaperConstant.INTENT_BOACK_REF_WORK.equals(intent.getAction())) {
                if (mChildPosition > -1 && mGroupPosition > -1) {
                    try {
                        float actual_score = intent.getFloatExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, 0);
                        int workStatus = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, 0);
                        WorkContents workContents = mCurrentMyWork.getWorkContents().get(mChildPosition);
                        if (workStatus == 16) {//听说模考显示评分中
                            workContents.setWorkStatus(16);
                        } else if (workStatus == 17) {//在线作答有主观题显示下划线。
                            workContents.setWorkStatus(17);
                        } else {
                            workContents.setSubmitCount(workContents.getSubmitCount());
                            workContents.setShowScore(actual_score + "");
                            homeWorkFragment.notifyDataSetChanged();
                        }
                    } catch (IndexOutOfBoundsException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mGroupPosition = -1;
                mChildPosition = -1;
                homeWorkFragment.refreshNetData(true);
            }
        }
    };

}
